﻿using Raven.Abstractions.Data;
using Raven.Client;
using Raven.Client.Connection;
using Raven.Client.Document;
using Raven.Client.Embedded;
using Raven.Client.FileSystem;
using Raven.Database.Server;
using Raven.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TestRavenDB.src;

namespace TestRavenDB
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        EmbeddableDocumentStore store = null;
        private void button1_Click(object sender, EventArgs e)
        {
            if (store == null)
            {
                store = new EmbeddableDocumentStore
                {
                    DataDirectory = @"C:\FS\100_Server\RavenDB\RavenDB-3.5.1\Server\Databases\zkc",
                    DefaultDatabase = "zkc"
                    //UseEmbeddedHttpServer = false,
                    // RunInMemory = false,

                };
            }


            try
            {
                store.Initialize();
                //          store.DatabaseCommands.GlobalAdmin.CreateDatabase(new DatabaseDocument
                //          {
                //              Id = "CompressedDB",            // Other configuration options omitted for simplicity
                //              Settings =   {
                //// ...
                //{ "Raven/ActiveBundles", "Compression" }
                //              }
                //          });

            }
            catch (Exception exp)
            {

                richTextBox1.AppendText(exp.Message);
            }
           // store.DefaultDatabase = "zkc";


            using (IDocumentSession session = store.OpenSession()) // opens a session that will work in context of 'DefaultDatabase'
            {
                FileStream fs = File.OpenRead(@"c:/temp/1.jpg");
                byte[] _bs = File.ReadAllBytes(@"c:/temp/1.jpg");
                Employee employee = new Employee
                {
                    FirstName = "John",
                    LastName = "Doe",
                    FileB = _bs
                };



                session.Store(employee); // stores employee in session, assigning it to a collection `Employees`
                string employeeId = employee.Id; // Session.Store will assign Id to employee, if it is not set

                session.SaveChanges(); // sends all changes to server
                employee = session.Load<Employee>(employeeId);
                File.WriteAllBytes(@"c:/temp/2.jpg", employee.FileB);

                var fstore = store.FilesStore.Url;

                //var fsession = fstore.OpenAsyncSession();
                ////UploadFiles(fsession);
                //var rs = openFileDialog1.ShowDialog();
                //if (rs == DialogResult.OK)
                //{
                //    UploadFiles(fsession, openFileDialog1.FileName);
                //    AppendText(openFileDialog1.FileName);
                //}

                AppendText(fstore);

                richTextBox1.AppendText("end");

                // Session implements Unit of Work pattern,
                // therefore employee instance would be the same and no server call will be made


            }


        }
        public async void UploadFiles(IAsyncFilesSession fsession, String file)
        {
            using (Stream content = File.OpenRead(file))
            {
                var name = new FileInfo(file);

                fsession.RegisterUpload("/" + name.Name, content);
                AppendText("/" + name.Name + "\r\n");

                await fsession.SaveChangesAsync();
            }
        }
        public async void AppendText(string str)
        {

            await Task.Run(() =>
            {
                Console.WriteLine("");
                this.Invoke((Action)delegate
                {
                    this.richTextBox1.AppendText(str + "\r\n");
                });

            });

        }

        private void button2_Click(object sender, EventArgs e)
        {
            //zkc database
            using (IDocumentStore store = new DocumentStore()
            {

                Url = @"~\App_Data"
            }.Initialize())
            {

                IDatabaseCommands commands = store.DatabaseCommands;
                IDatabaseCommands zkcCommands = commands.ForDatabase("zkc");

                var re = zkcCommands.Put("categories/999", null, RavenJObject.FromObject(new Category
                {
                    Name = "My Category",
                    Description = "My Category description"
                }), new RavenJObject());
                using (IDocumentSession zkcSession = store.OpenSession("zkc"))
                {

                }

            }

            richTextBox1.AppendText("end");
        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {

        }
    }

    internal class Employee
    {
        public string FirstName { get; internal set; }
        public string Id { get; internal set; }
        public string LastName { get; internal set; }
        public byte[] FileB { get; set; }
    }
}
